﻿using orderCreater.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace orderCreater
{
    public partial class FrmWdhZc : Form
    {
        public OrderCreaterModel OCM = new OrderCreaterModel();
        public WDH_CreaterModel OCM_WDH = new WDH_CreaterModel();
        private AreaRang _areaRang = new AreaRang();
        public FrmWdhZc()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.sr_bgw.WorkerSupportsCancellation = true;        
            this.sr_btn_stop.Enabled = false;
            this.sr_tb_goodIds.Text = ConfigurationManager.AppSettings["goodsIds-wdhZc"];
            this.bindCityList();
        }

        private void bindCityList()
        {
            cb_city_list.DataSource = AddressRang.SendRang;
            cb_city_list.ValueMember = "cityId";
            cb_city_list.DisplayMember = "cityName";
        }
       
        private void sr_bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;
            this.sr_btn_start.Enabled = false;
            this.sr_btn_stop.Enabled = true;
            this.sr_tb_priceArea.Enabled = false;
            this.sr_tb_goodIds.Enabled = false;
            this.sr_dt_time.Enabled = false;
            this.sr_tb_logs.Text = "";

            decimal total = 0;
            int count = 0,post_err_cnt = 0;
            StringBuilder _logs = new StringBuilder();
            string cityids = cb_city_list.SelectedValue.ToString();
            do
            {
                if (worker.CancellationPending || total > decimal.Parse(this.sr_tb_priceArea.Text))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    ///获取新增用户
                    WDH_REGISTER new_user = cb_user.Checked ? OCM.WDHExistUser() : OCM.WDHNewUser();
                    if (new_user.status == 200)
                    {
                        ///获取收货地址
                        string area_ids = this._areaRang.getSendRangStr();
                        WDH_AddrRange new_addr = OCM.WDHRangeAddr(area_ids);
                        if (new_addr.status == 200 && new_addr.data.Count > 0)
                        {
                            Db_member buyer = OCM_WDH.SelectBuyerById(new_user.data.member_id);
                            Db_goods goods = OCM_WDH.SelectGoodsByIds(this.sr_tb_goodIds.Text);

                            string orderTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            string payTime = OCM.CreatePayTime(orderTime, tb_jiange.Text);
                            if (bd_cb.Checked)
                            {
                                orderTime = OCM.CreateOrderTime(this.sr_dt_time.Value.ToString("yyyy-MM-dd"));
                            }

                            Db_order add_order = new Db_order();
                            add_order.orderCode = OCM.CreateOrderCode();
                            add_order.memberId = Convert.ToInt32(new_user.data.member_id);
                            add_order.shopId = 0;
                            add_order.accepterName = new_addr.data[0].name;
                            add_order.accepterMobile = new_addr.data[0].mobile;
                            add_order.provinceId = Convert.ToInt32(new_addr.data[0].province_id);
                            add_order.cityId = Convert.ToInt32(new_addr.data[0].city_id);
                            add_order.districtId = Convert.ToInt32(new_addr.data[0].area_id);
                            add_order.address = new_addr.data[0].address;

                            add_order.payTime = Convert.ToDateTime(payTime);
                            add_order.expressPrice = 0;
                            add_order.totalPrice = goods.goodsPrice;
                            add_order.orderRemarks = OCM.getWDHOrderRemark();
                            add_order.ref1score = 0;
                            add_order.ref2score = 0;
                            add_order.ref3score = 0;
                            add_order.isView = 0;
                            add_order.isIntegral = 0;
                            add_order.arrivedTime = Convert.ToDateTime(OCM.CreateSendTime(orderTime));
                            add_order.addTime = Convert.ToDateTime(orderTime);
                            add_order.isQiangDan = 0;
                            add_order.is_zc = 1;
                            add_order.type_status = 2;

                            if (OCM.IsPay())
                            {
                                add_order.payStatusId = 2;
                                add_order.deliveryStatusId = 1;
                                add_order.orderStatusId = 2;
                                add_order.payTypeId = 2;
                            }
                            else
                            {
                                add_order.payStatusId = 1;
                                add_order.deliveryStatusId = 1;
                                add_order.orderStatusId = 1;
                                add_order.payTypeId = 0;
                            }
                            string order_id = OCM_WDH.AddOrder(add_order);
                            if (order_id != "" && order_id != "" && order_id != "-1")
                            {
                                //添加到订单商品表
                                Db_order_item o_item = new Db_order_item();
                                o_item.orderId = add_order.orderId;
                                o_item.goodsId = goods.goodsId;
                                o_item.goodsName = goods.goodsName;
                                o_item.goodsPrice = goods.goodsPrice;
                                o_item.goodsLogoUrl = "http://app.wodinghua.com" + goods.goodsLogo;
                                o_item.goodsQuantity = 1;
                                o_item.promotionType = 0;
                                o_item.expressPrice = 0;
                                o_item.goodsStandard = goods.goodsSub;
                                OCM_WDH.AddOrderItem(o_item);
                                //用户使用次数加1
                                OCM.WDHUpdateUserBuyCount(new_user.data.member_id);
                                //收货地址使用次数加1
                                OCM.WDHUpdateAddressCount(new_addr.data[0].id);

                                //插入到运行日志中
                                _logs.Insert(0, new_addr.data[0].name + " " + new_addr.data[0].mobile + " " + new_addr.data[0].province_id + " " + new_addr.data[0].city_id + " " + new_addr.data[0].area_id + " " + new_addr.data[0].address + "\r\n");
                                this.sr_tb_logs.Text = _logs.ToString();

                                //同步到支付宝
                                if (this.sync_alipay_cb.Checked && OCM.IsPay())
                                {
                                    syncAlipay(add_order.orderId.ToString(), goods.goodsPrice.ToString(), buyer.memberMobile, buyer.realName, payTime);
                                }

                                total = OCM_WDH.SelectTotalPrice(this.sr_dt_time.Value.ToShortDateString());
                                decimal total_pay = OCM_WDH.SelectTotalPay(this.sr_dt_time.Value.ToShortDateString());
                                count += 1;
                                _logs.Insert(0, "[" + DateTime.Now + "]成功录入一条订单信息。\r\n");
                                this.sr_lb_status.Text = "运行中……";
                                this.sr_tb_logs.Text = _logs.ToString();
                                this.sr_lb_count.Text = count.ToString();
                                this.sr_lb_totalPrice.Text = total.ToString();
                                this.lb_sr_pay.Text = total_pay.ToString();
                            }

                            //string _totalStr = OCM.ExecuteMySql("SELECT sum(o.totalprice) from db_order as o LEFT JOIN db_order_item oi on o.orderId=oi.orderId where oi.goodsId in(" + this.sr_tb_goodIds.Text + ") and o.cityId='" + this.cb_city_list.SelectedValue + "' and o.addTime>'" + _s_time + "' and o.addTime<'" + _e_time + "' and o.is_zc=1;");
                            //string _totalPay = OCM.ExecuteMySql("SELECT sum(o.totalprice) from db_order as o LEFT JOIN db_order_item oi on o.orderId=oi.orderId where oi.goodsId in(" + this.sr_tb_goodIds.Text + ") and o.payStatusId=2 and o.cityId='" + this.cb_city_list.SelectedValue + "' and o.addTime>'" + _s_time + "' and o.addTime<'" + _e_time + "' and o.is_zc=1;");
                            if (bd_cb.Checked != true)
                            {
                                Random rd_sl = new Random();
                                int t_sl = rd_sl.Next(20 * 1000, Int32.Parse(this.tb_jiange.Text) * 1000);
                                System.Threading.Thread.Sleep(t_sl);
                            }
                        }
                        else
                        {
                            _logs.Insert(0, "[" + DateTime.Now + "]获取收货地址失败："+new_addr.msg+"。\r\n");
                            this.sr_tb_logs.Text = _logs.ToString();
                            post_err_cnt++;
                            if (post_err_cnt > 10) {
                                this.sr_lb_status.Text = "停止中……";
                                sr_bgw.CancelAsync();
                            }
                        }
                    }
                    else
                    {
                        _logs.Insert(0, "[" + DateTime.Now + "]获取下单人信息失败：" + new_user.msg + "。\r\n");
                        this.sr_tb_logs.Text = _logs.ToString();
                        post_err_cnt++;
                        if (post_err_cnt > 10)
                        {
                            this.sr_lb_status.Text = "停止中……";
                            sr_bgw.CancelAsync();
                        }
                    }     
                }
            } while (!worker.CancellationPending);

            this.sr_lb_status.Text = "已停止！";

            this.sr_btn_start.Enabled = true;

            this.sr_btn_stop.Enabled = false;

            this.sr_tb_priceArea.Enabled = true;

            this.sr_tb_goodIds.Enabled = true;

            this.sr_dt_time.Enabled = true;
            
        }

        private void sr_bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                this.sr_lb_status.Text = "已停止！";
            }
        }

        private void sr_btn_start_Click(object sender, EventArgs e)
        {
            if (this.sr_tb_priceArea.Text.Length < 1) 
            {
                MessageBox.Show("请输入当日总金额。");
            }
            else if (this.sr_tb_goodIds.Text.Length < 1)
            {
                MessageBox.Show("请输入产品ID。");
            }
            else if (this.cb_city_list.Text.Length < 1)
            {
                MessageBox.Show("请选择城市");
            }
            else 
            {
                this.sr_lb_status.Text = "系统初始化中……";

                this.sr_bgw.RunWorkerAsync();
            }
            
        }

        private void sr_btn_stop_Click(object sender, EventArgs e)
        {
            this.sr_lb_status.Text = "停止中……";

            sr_bgw.CancelAsync();
        }

        public static string syncAlipay(string _orderSn, string _orderPrice, string _account, string _fullName, string _tradeTime)
        {
            try
            {
                string url = "orderNo=" + _orderSn + "&";
                url = url + "tradeAmount=" + _orderPrice + "&";
                url = url + "otherAccountEmail=" + _account + "&";
                url = url + "otherAccountFullname=" + _fullName + "&";
                url = url + "sourceType=" + 2 + "&"; // 来源:1为531,2为我订花
                url = url + "tradeTime=" + _tradeTime;

                // string formUrl = "http://sync?.qqxhsd.com/api/trade/add";
                string formUrl = "https://alipay.22ca.com/index.php/Api/insertOrder3";
                string formData = url;                               //提交的参数

                //注意提交的编码 这边是需要改变的 这边默认的是Default：系统当前编码
                byte[] postData = Encoding.UTF8.GetBytes(formData);

                // 设置提交的相关参数 
                HttpWebRequest request = WebRequest.Create(formUrl) as HttpWebRequest;
                Encoding myEncoding = Encoding.UTF8;
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.ContentLength = postData.Length;

                // 提交请求数据 
                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();

                HttpWebResponse response;
                Stream responseStream;
                StreamReader reader;
                string srcString;
                response = request.GetResponse() as HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
                srcString = reader.ReadToEnd();
                string result = srcString;   //返回值赋值
                reader.Close();
                return result;
            }
            catch
            {
                return "error";
            }
        }

        private void cb_city_list_SelectedValueChanged(object sender, EventArgs e)
        {
            //如果选中
            if (cb_city_list.SelectedIndex > 0)
            {
                string selectCityId = cb_city_list.SelectedValue.ToString();
                for (int i = 0; i < AddressRang.SendRang.Count; i++)
                {
                    if (AddressRang.SendRang[i].cityId == selectCityId)
                    {
                        this._areaRang.SendRang = AddressRang.SendRang[i].areaList; // 设置配送的区域范围
                        break;
                    }
                }
            }
        }

        private void bd_cb_CheckedChanged(object sender, EventArgs e)
        {
            if (this.bd_cb.Checked == true)
            {
                this.sr_dt_time.Enabled = true;
            }
            else
            {
                this.sr_dt_time.Enabled = false;

            }
        }

        private void sr_tb_priceArea_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键  
            {
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字  
                {
                    e.Handled = true;
                }
            }
        }
    }
}
